package com.augurit.common.calendar.service.impl;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.orm.Page;
import org.springside.modules.orm.PropertyFilter;

import com.augurit.common.calendar.convert.SysCalendarConvertor;
import com.augurit.common.calendar.service.ISysCalSharedService;
import com.augurit.common.calendar.service.ISysCalendarService;
import com.augurit.common.calendar.web.form.SysCalSharedForm;
import com.augurit.common.calendar.web.form.SysCalendarForm;
import com.augurit.common.dao.OmOrgDao;
import com.augurit.common.dao.OmUserDao;
import com.augurit.common.dao.SysCalSharedDao;
import com.augurit.common.dao.SysCalendarDao;
import com.augurit.common.entity.SysCalShared;
import com.augurit.common.entity.SysCalendar;
import com.augurit.common.system.web.org.form.OmOrgForm;
import com.augurit.common.system.web.org.form.OmUserForm;
import com.augurit.common.util.HqlUtils;
import com.augurit.common.util.PageUtils;
import com.augurit.common.util.lang.StringUtils;

@Service
@Transactional
public class SysCalendarServiceImpl implements ISysCalendarService{

	@Autowired
	private ISysCalSharedService sysCalSharedService;
	
	@Autowired
	private SysCalendarDao sysCalendarDao;
	@Autowired
	private SysCalSharedDao sysCalSharedDao;
	
	@Autowired
	private OmOrgDao  omOrgDao;
	@Autowired
	private OmUserDao omUserDao;
	
	/**
	 * 根据主键获取Form对象
	 */
	@Transactional(readOnly = true)
	public SysCalendarForm get(Long id) {
		SysCalendar entity = sysCalendarDao.get(id);
		return SysCalendarConvertor.convertVoToForm(entity);
	}
	
	/**
	 * 删除Form对象列表
	 */
	public void delete(Long... ids) {
		sysCalendarDao.delete(ids);
	}
	
	/**
	 * 
	 * @param ids
	 */
	public void deleteCascade(Long... ids){
		if(ids != null && ids.length > 0){
			for(Long id: ids){
				List<SysCalShared> shares = sysCalSharedDao.findBy("eventId", id);
				if(shares != null && shares.size() > 0)
					sysCalSharedDao.delete(shares);
				sysCalendarDao.delete(id);
			}
		}
	}

	/**
	 * 保存新增或修改的Form对象列表
	 */
	public void save(SysCalendarForm... forms) {
		if(forms != null)
			for(SysCalendarForm form : forms)
				this.save(form);
	}
	
	/**
	 * 保存新增或修改的Form对象
	 */
	public void save(SysCalendarForm form){
		
		if(form != null){
			SysCalendar entity = null;
			
			//准备VO对象
			if(form != null && form.getEventId() != null){
				entity = sysCalendarDao.get(form.getEventId());
			}else{
				entity = new SysCalendar();
			}
			
			//属性值转换
			SysCalendarConvertor.convertFormToVo(form, entity);
			
			//保存
			sysCalendarDao.save(entity);
			
			//回填ID属性值
			form.setEventId(entity.getEventId());
		}
	}
	
	/**
	 * 添加日程事件
	 * @param form 
	 */
	public void addCalendarEvent(SysCalendarForm form)throws ParseException{
		if(form != null){
			//如果不是整天，重新设置开始时间、结束时间
			if(StringUtils.isBlank(form.getIsAllDay())){
				form.reSetStartDate();
				form.reSetEndDate();
			}
			//否则设置为整天
			else{
				form.setIsAllDay("true");
			}
			if(form.getIsPublic() != null && form.getIsPublic().equals("true")){
				form.setIsPublic("Y");
			}
			else{
				form.setIsPublic("N");
			}
			
			this.save(form);
			sysCalSharedService.save(form.getEventId(), form.getSharedUserIds(), form.getShareTypes());
		}
	}

	/**
	 * 根据Form对象的查询条件作分页查询
	 */
	@Transactional(readOnly = true)
	public Page<SysCalendarForm> search(Page<SysCalendarForm> page, SysCalendarForm form) {
		// 建立新的分页对象
		Page pg = PageUtils.newPageInstance(page);
		
		// 查询语句及参数
		StringBuffer hql = new StringBuffer("from SysCalendar ps where 1=1");
		List values = new ArrayList();
		
		// 查询条件
		if(form != null){
			
		}
		
		//排序
		hql.append(HqlUtils.buildOrderBy(page, "ps"));
		
		// 执行分页查询操作
		sysCalendarDao.findPage(pg, hql.toString(), values);
		
		// 转换为Form对象列表并赋值到原分页对象中
		List<SysCalendarForm> list = SysCalendarConvertor.convertVoListToFormList(pg.getResult());
		PageUtils.copy(pg, list, page);
		return page;
	}
	
	/**
	 * 获取所有的日程事件
	 * @return
	 */
	@Transactional(readOnly = true)
	public List<SysCalendarForm> getAllCaEvents(){
		List<SysCalendar> entities = sysCalendarDao.getAll();
		return SysCalendarConvertor.convertVoListToFormList(entities);
	}
	
	
	/**
	 * 根据过滤条件列表作分页查询
	 */
	@Transactional(readOnly = true)
	public Page<SysCalendarForm> search(Page<SysCalendarForm> page, List<PropertyFilter> filters) {
		// 建立新的分页对象
		Page<SysCalendar> pg = PageUtils.newPageInstance(page);
		
		// 按过滤条件分页查找对象
		sysCalendarDao.findPage(pg, filters);
		
		// 转换为Form对象列表并赋值到原分页对象中
		List<SysCalendarForm> list = SysCalendarConvertor.convertVoListToFormList(pg.getResult());
		PageUtils.copy(pg, list, page);
		return page;
	}
	
	
	public List<SysCalendarForm> getSharedEvents(Long userId){
		if(userId != null){
			String hql = "select cal, user.userName, share.shareType, user2.userName from SysCalendar cal, SysCalShared share, OmUser user, OmUser user2 where user.userId=cal.ownerId and user2.userId=cal.creatorId and cal.eventId = share.eventId and share.shareUserId=?";
			List<Object[]> objs = sysCalendarDao.find(hql, userId);
			return SysCalendarConvertor.convertObjsToFormList(objs);
		}
		return null;
	}
	
	/**
	 * 获取某个公共的日程
	 * @return
	 */
	public List<SysCalendarForm> getPublicEvents(){
		String hql = "select cal, user.userName, user2.userName from SysCalendar cal, OmUser user, OmUser user2 where user.userId=cal.ownerId and user2.userId=cal.creatorId  and cal.isPublic = 'Y' ";
		List<Object[]> objs = sysCalendarDao.find(hql);
		
		List<SysCalendarForm> forms = null;
		if(objs != null && objs.size() > 0){
			forms = new ArrayList<SysCalendarForm>();
			for(Object[] obj:objs){
				SysCalendar entity = (SysCalendar)obj[0];
				String ownerName = (String)obj[1];
				String creatorName = (String)obj[2];
				
				SysCalendarForm form = SysCalendarConvertor.convertVoToForm(entity);
				form.setOwnerName(ownerName);
				form.setCreatorName(creatorName);
				
				forms.add(form);
			}
		}
		return forms;
	}
	
	/**
	 * 获取某个用户自己的日程
	 * @return
	 */
	public List<SysCalendarForm> getOwnEvents(Long userId){
		String hql = "select cal, user.userName, user2.userName from SysCalendar cal, OmUser user, OmUser user2 where user.userId=cal.ownerId and user2.userId=cal.creatorId and cal.ownerId = ? ";
		List<Object[]> objs = sysCalendarDao.find(hql, userId);
		
		List<SysCalendarForm> forms = null;
		if(objs != null && objs.size() > 0){
			forms = new ArrayList<SysCalendarForm>();
			for(Object[] obj:objs){
				SysCalendar entity = (SysCalendar)obj[0];
				String userName = (String)obj[1];
				String creatorName = (String)obj[2];
				
				SysCalendarForm form =  SysCalendarConvertor.convertVoToForm(entity);
				form.setOwnerName(userName);
				form.setCreatorName(creatorName);
				form.setCanEdit(true);
				forms.add(form);
				
			}
		}
		return forms;
	}
	
	/**
	 * 获取用户创建的日程
	 * @param userId
	 * @return
	 */
	public List<SysCalendarForm> getCreateEvents(Long userId){
		String hql = "select cal, user.userName, user2.userName from SysCalendar cal, OmUser user, OmUser user2  where user.userId=cal.ownerId and cal.creatorId=user2.userId and cal.creatorId = ? ";
		List<Object[]> objs = sysCalendarDao.find(hql, userId);
		
		List<SysCalendarForm> forms = null;
		if(objs != null && objs.size() > 0){
			forms = new ArrayList<SysCalendarForm>();
			for(Object[] obj:objs){
				SysCalendar entity = (SysCalendar)obj[0];
				String ownerName = (String)obj[1];
				String creatorName = (String)obj[2];
				
				SysCalendarForm form = SysCalendarConvertor.convertVoToForm(entity);
				form.setOwnerName(ownerName);
				form.setCreatorName(creatorName);
				
				forms.add(form);
				
			}
		}
		return forms;
	}
	
	/**
	 * 获取某一个用户可以编辑、可以读的事件
	 * @param userId
	 * @return
	 */
	public List<SysCalendarForm> getAllEvents(Long userId){
		Set<SysCalendarForm> result = new HashSet<SysCalendarForm>();
		
		List<SysCalendarForm> sharedEvents = this.getSharedEvents(userId);
		if(sharedEvents != null && sharedEvents.size() > 0){
			result.addAll(sharedEvents);
		}
		List<SysCalendarForm> ownedEvents = this.getOwnEvents(userId);
		if(ownedEvents != null && ownedEvents.size() > 0){
			result.addAll(ownedEvents);
		}
		
		List<SysCalendarForm> createEvents = this.getCreateEvents(userId);
		if(createEvents != null && createEvents.size() > 0){
			result.addAll(createEvents);
		}
		
		List<SysCalendarForm> publicEvents = this.getPublicEvents();
		if(publicEvents != null && publicEvents.size() > 0){
			result.addAll(publicEvents);
		}
		return new ArrayList<SysCalendarForm>(result);
	}
	
	/**
	 * 获取一个用户可以编辑的事件
	 * @param userId
	 * @return
	 */
	public List<SysCalendarForm> getCanEditEvents(Long userId){
		if(userId != null){
			String hql = "select cal from SysCalendar cal, SysCalShared share where cal.eventId = share.eventId and share.shareUserId=? and shareType = ?";
			List<SysCalendar> entities = sysCalendarDao.find(hql, userId, SysCalSharedForm.WRITE_SHARE_TYPE);
			return SysCalendarConvertor.convertVoListToFormList(entities);
		}
		return null;
	}
	
	/**
	 * 获取一个用户可以阅读的事件
	 * @param userId
	 * @return
	 */
	public List<SysCalendarForm> getCanReadEvents(Long userId){
		if(userId != null){
			String hql = "select cal from SysCalendar cal, SysCalShared share where cal.eventId = share.eventId and share.shareUserId=? and shareType = ?";
			List<SysCalendar> entities = sysCalendarDao.find(hql, userId, SysCalSharedForm.READ_SHARE_TYPE);
			return SysCalendarConvertor.convertVoListToFormList(entities);
		}
		return null;
	}
	
	/**
	 * 构建机构用户树
	 * @param 
	 */
	@Transactional(readOnly = true)
	private OmOrgForm constructOrgTree(OmOrgForm curOrg){
		List<OmOrgForm> childOrgs = omOrgDao.getChildOrgs(curOrg.getOrgId());
		curOrg.setChildren(childOrgs);
		
		List<OmUserForm> childUsers = omUserDao.getUsersByOrgId(curOrg.getOrgId());
		curOrg.setUsers(childUsers);
		
		if(childOrgs != null && childOrgs.size() > 0){
			for(OmOrgForm childOrg:childOrgs){
				constructOrgTree(childOrg);
			}
		}
		
		return curOrg;
	}
	
	/**
	 * 获取机构用户树
	 * @return
	 */
	@Transactional(readOnly = true)
	public List<OmOrgForm> getOrgUserTree(){
		List<OmOrgForm> result = null;
		List<OmOrgForm> topOrgs = omOrgDao.getTopOrgs();
		if(topOrgs != null && topOrgs.size() > 0){
			result = new ArrayList<OmOrgForm>();
			for(OmOrgForm org:topOrgs){
				OmOrgForm orgForm = constructOrgTree(org);
				result.add(orgForm);
			}
		}
		return result;
	}
}
